package com.fbty.mt.action;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import com.fbty.base.action.BaseAction;
import com.fbty.base.domain.Page;
import com.fbty.mt.dao.PwdTempDao;
import com.fbty.mt.domain.Announcement;
import com.fbty.mt.domain.Answer;
import com.fbty.mt.domain.CheckInfo;
import com.fbty.mt.domain.IndexPrice;
import com.fbty.mt.domain.News;
import com.fbty.mt.domain.Parms;
import com.fbty.mt.domain.PwdTemp;
import com.fbty.mt.domain.User;
import com.fbty.mt.domain.UserInfo;
import com.fbty.mt.service.ProxyService;
import com.fbty.mt.service.WelcomService;
import com.fbty.mt.utils.EmailUtil;
import com.fbty.mt.utils.IPInfoHelper;

public class WelcomeAction extends BaseAction{
	private UserInfo info;
	private Answer answer;
	private String message;
	private Integer state = 0; //0显示所有. 1表示未处理，2表示已处理
	private Page page;
	private Parms parms;
	private int pageNo=1;
	private String value;
	private Integer id;
	private int pageSize=20;
	private WelcomService welcomeService;
	private ProxyService proxyService;
	private List<IndexPrice> priceList; //前台价格显示
	private String verifycode; //验证码
	private String ip; //测试ip
	private String port; //端口
	private String type; //访问类型
	private List<News> news;
	private List<Announcement> anns;
	private Integer pid;
	private Integer num;
	private Integer price;
	private Map<String, String> objMap; //某一个新闻或公告
	private PwdTempDao pwdTempDao;
	private Long validTime;
	/**
	 * 首页登陆
	 * @return
	 */
	public String welcome(){
		List<Parms> list = welcomeService.getList(); //得到首页需要的qq,email,phone
		for(Parms parms : list) {
			if("adminQQ".equals(parms.getTitle())) {
				sessionMap.put("adminQQ",parms.getValue());
			} else if("adminEmail".equals(parms.getTitle())) {
				sessionMap.put("adminEmail",parms.getValue());
			} else if("adminPhone".equals(parms.getTitle())) {
				sessionMap.put("adminPhone",parms.getValue());
			}
		}
		UserInfo userInfo = new UserInfo();
		String brows = request.getHeader("user-agent");
		String userBrows = "";
		if(brows.indexOf("Chrome") != -1) {
			userBrows = "Chrome/谷歌";
		} else if(brows.indexOf("Firefox") != -1) {
			userBrows = "Firefox/火狐";
		} else if(brows.indexOf("MSIE 6.0") != -1) {
			userBrows = "Internet Explorer 6";
		}  else if(brows.indexOf("MSIE 7.0") != -1) {
			userBrows = "Internet Explorer 7";
		}   else if(brows.indexOf("MSIE 8.0") != -1) {
			userBrows = "Internet Explorer 8";
		}   else if(brows.indexOf("MSIE 9.0") != -1) {
			userBrows = "Internet Explorer 9";
		}   else if(brows.indexOf("MSIE 10.0") != -1) {
			userBrows = "Internet Explorer 10";
		} else {
			userBrows = brows;
		}
		
		userInfo.setUserOs(getClientOS(brows));  
		userInfo.setBrows(userBrows);
		userInfo.setUserName(System.getProperty("user.name"));
		userInfo.setIp(request.getRemoteAddr());
//		InetAddress address;
//		try {
//			address = InetAddress.getLocalHost();
//			userInfo.setIp(address.getHostAddress());  
//		} catch (UnknownHostException e) {
//			e.printStackTrace();
//		}  
		page = welcomeService.showPrice(pageNo, pageSize); //得到价格
		news = welcomeService.showNews(); //得到新闻
		anns = welcomeService.showAnns();//得到公告
		info = userInfo;
		sessionMap.put("brows",info.getBrows());
		sessionMap.put("useros",info.getUserOs());
		sessionMap.put("userloginip",info.getIp());
		return SUCCESS;
	}
	/**
     * 获取客户端操作系统信息，目前只匹配Win 7、WinXP、Win2003、Win2000、MAC、WinNT、Linux、Mac68k、Win9x
     * @param userAgent request.getHeader("user-agent")的返回值
     * @return
     */

	public static String getClientOS(String userAgent){
        String cos = "unknow os";
        
       Pattern p = Pattern.compile(".*(Windows NT 6\\.1).*");
        Matcher m = p.matcher(userAgent);
        if(m.find())
        {
            cos = "Windows 7";
            return cos;
        }
        
       p = Pattern.compile(".*(Windows NT 5\\.1|Windows XP).*");
        m = p.matcher(userAgent);
        if(m.find())
        {
            cos = "Windows XP";
            return cos;
        }
        
       p = Pattern.compile(".*(Windows NT 5\\.2).*");
        m = p.matcher(userAgent);
        if(m.find())
        {
            cos = "Windows 2003";
            return cos;
        }
        
       p = Pattern.compile(".*(Win2000|Windows 2000|Windows NT 5\\.0).*");
        m = p.matcher(userAgent);
        if(m.find())
        {
            cos = "Windows 2000";
            return cos;
        }
        
       p = Pattern.compile(".*(Mac|apple|MacOS8).*");
        m = p.matcher(userAgent);
        if(m.find())
        {
            cos = "MAC";
            return cos;
        }
        
       p = Pattern.compile(".*(WinNT|Windows NT).*");
        m = p.matcher(userAgent);
        if(m.find())
        {
            cos = "Windows NT";
            return cos;
        }
        
       p = Pattern.compile(".*Linux.*");
        m = p.matcher(userAgent);
        if(m.find())
        {
            cos = "Linux";
            return cos;
        }
        
       p = Pattern.compile(".*(68k|68000).*");
        m = p.matcher(userAgent);
        if(m.find())
        {
            cos = "Mac68k";
            return cos;
        }
        
       p = Pattern.compile(".*(9x 4.90|Win9(5|8)|Windows 9(5|8)|95/NT|Win32|32bit).*");
        m = p.matcher(userAgent);
        if(m.find())
        {
            cos = "Windows 9x";
            return cos;
        }
        
       return cos;
    }

	public String select() throws Exception {
		return SUCCESS;
	}
	public String selectPost() throws Exception {
		if(id == null || id==1 || id==0) {
			return "selectPost";
		}
		if(id==2) {
			return "selectPost2";
		} else if(id==3) {
			return "selectPost3";
		} else if(id==4) {
			return "selectPost4";
		} else {
			return "selectPost";
		}
	}
	public String saveSnswer() throws Exception {
		answer.setState(1);
		welcomeService.saveAnswer(answer);
		message = "保存成功,我们会尽快回复您!";
		return SUCCESS;
	}
	/**
	 * socks5测试
	 * @return
	 * @throws Exception
	 */
	public String sockTest() throws Exception {
		String code = (String)sessionMap.get("code");
		if(code==null || "".equals(code) || !code.equalsIgnoreCase(verifycode)) {
			message = "验证码不正确!";
			return SUCCESS;
		}
		String ipReq = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."                  
			+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."                  
			+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."                  
			+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$"; 
		Pattern ipPattern=Pattern.compile(ipReq); 
		Matcher matcher=ipPattern.matcher(ip==null?"":ip); 
		if(ip == null || "".equals(ip) || !matcher.matches()){
			message = "检证ip格式不正确!";
			return SUCCESS;
		}
		if(port == null || "".equals(port)){
			message = "端口格式不正确!";
			return SUCCESS;
		}
		Integer portReg = 8080;
		try {
			portReg = Integer.parseInt(port);
			if(portReg>8080 || portReg < 1080) {
				message = "端口格式不正确!";
				return SUCCESS;
			}
			
		} catch (Exception e) {
			message = "端口格式不正确!";
			return SUCCESS;
		}
		Integer  proxyType = 0;
		if("socks5".equalsIgnoreCase(type)) {
			proxyType = CheckInfo.SOCKS5_PROXY;
		} else if("socks4".equalsIgnoreCase(type)) {
			proxyType = CheckInfo.SOCKS4_PROXY;
		} else if("http".equalsIgnoreCase(type)) {
			proxyType = CheckInfo.HTTP_PROXY;
		} else if("https".equalsIgnoreCase(type)) {
			proxyType = CheckInfo.HTTPS_PROXY;
		}
		CheckInfo checkInfo = proxyService.checkConnection(ip,portReg, proxyType);
		Map<String, String> map = IPInfoHelper.getIPInfo(ip);
		Map<String, String> value = new HashMap<String, String>();
		if(checkInfo.getReslut() == 0) {
			value.put("延迟", checkInfo.getDelay()+"");
			value.put("国家", map.get("Country"));
			value.put("地区", map.get("Region"));
			value.put("城市", map.get("City"));
			message = value.toString();
		} else if(checkInfo.getReslut() ==CheckInfo.NO_PROXY) {
//			public static final int PROXY_CHECK_SUCCESS = 0 ;  //代理检测成功，除此以外的表示都为失败
//			public static final int NO_PROXY = 1 << 16;  //代理不存在
//			public static final int PROXY_NO_CONNECT = 2 << 16; //代理无法连接
//			public static final int PROXY_IO_ERROR = 3 << 16; //代理IO输出错误
//			public static final int PROXY_AUTH_FAILURE = 4 << 16; //代理鉴权失败，帐号或者密码错误
//			public static final int PROXY_CHECK_FAILURE = 5 << 16; //代理检测网址失败，即本地到代理服务器是正常的，但是通过代理到监测地址存在异常
//			public static final int UNKNOWN_EXCEPTION = 6 << 16; //未知异常，程序内部错误
			message = "代理不存在";
		} else if(checkInfo.getReslut() ==CheckInfo.PROXY_NO_CONNECT) {
			message = "代理无法连接";
		} else if(checkInfo.getReslut() ==CheckInfo.PROXY_IO_ERROR) {
			message = "代理IO输出错误";
		} else if(checkInfo.getReslut() ==CheckInfo.PROXY_AUTH_FAILURE) {
			message = "代理鉴权失败，帐号或者密码错误";
		} else if(checkInfo.getReslut() ==CheckInfo.PROXY_CHECK_FAILURE) {
			message = "代理检测网址失败，即本地到代理服务器是正常的，但是通过代理到监测地址存在异常";
		} else {
			message = "未知异常，程序内部错误";
		}
		return SUCCESS;
	}
	/**
	 * 用户提问--更新操作
	 * @return
	 * @throws Exception
	 */
	public String updateAnswer() throws Exception {
		welcomeService.updateAnswer(id);
		return SUCCESS;
	}
	/**
	 * 用户提问--删除操作
	 * @return
	 * @throws Exception
	 */
	public String deleteAnswer() throws Exception {
		welcomeService.deleteAnswer(id);
		return SUCCESS;
	}
	/**
	 * 前台价格设定
	 * @return
	 * @throws Exception
	 */
	public String showPrice() throws Exception {
		page = welcomeService.showPrice(pageNo, pageSize);
		return SUCCESS;
	}
	/**
	 * 管理保存价格设定
	 * @return
	 * @throws Exception
	 */
	public String updateIndexPrice() throws Exception {
		IndexPrice indexPrice = new IndexPrice();
		indexPrice.setId(pid);
		indexPrice.setNum(num);
		indexPrice.setPrice(price);
		indexPrice.setState(state);
		welcomeService.updateIndexPrice(indexPrice);
		return SUCCESS;
	}
	
	public String lookNews() throws Exception {
		if(id !=null) {
			objMap = welcomeService.findById(id, type);	
		}
		return SUCCESS;
	}
	
	public String course() throws Exception {
		String view = "error";	
		if(id != null ) {
		switch (id) {
			case 1:
				view = "SocksCap";
				break;
			case 2:
				view = "Proxifier";		
					break;
			case 3:
				view = "ProxyCap";
				break;
			case 4:
				view = "Easy2Game";
				break;
			default:
				
				break;
			}
		}
		return view;
	}
	public String lookAll() throws Exception {
		page = welcomeService.findAll(pageNo,10,type);
		return SUCCESS;
	}
	public String showAnswer() throws Exception{
		page = welcomeService.pageAnswer(pageNo, pageSize,state);
		return SUCCESS;
	}
	public String showParms() throws Exception {
		page = welcomeService.pageParms(pageNo, pageSize);
		return SUCCESS;
	}
	public String saveParms() throws Exception {
		welcomeService.saveParms(id,value);
		return SUCCESS;
	}
	public String answer() throws Exception{
		return SUCCESS;
	}
	
	public String checkup() throws Exception {
		return SUCCESS;
	}
	
	public String socks() throws Exception{
		return SUCCESS;
	}
	public String lead() throws Exception{
		return SUCCESS;
	}
	public String ssn() throws Exception{
		return SUCCESS;
	}
	public String our() throws Exception{
		return SUCCESS;
	}
	//重置密码
	public String updatePwd() throws Exception {
		if(pid == null || message == null) {
			return "error";
		}
		welcomeService.updatePwd(pid, message);
		state =  3;
		page = welcomeService.showPrice(pageNo, pageSize); //得到价格
		news = welcomeService.showNews(); //得到新闻
		anns = welcomeService.showAnns();//得到公告
		List<Parms> list = welcomeService.getList(); //得到首页需要的qq,email,phone
		for(Parms parms : list) {
			if("adminQQ".equals(parms.getTitle())) {
				sessionMap.put("adminQQ",parms.getValue());
			} else if("adminEmail".equals(parms.getTitle())) {
				sessionMap.put("adminEmail",parms.getValue());
			} else if("adminPhone".equals(parms.getTitle())) {
				sessionMap.put("adminPhone",parms.getValue());
			}
		}
		return SUCCESS;
	}
	public String reset() throws Exception {
		if(id==null && validTime == null) {
			return "error";
		}
		pid = (id/250)-56289;
		PwdTemp pwd = pwdTempDao.get(pid);
		if(pwd == null){
			return "error";
		}
		if(pwd.getValidTime() != (validTime-98419)) {
			return "error";
		}
		pid = pwd.getUserId();
		page = welcomeService.showPrice(pageNo, pageSize); //得到价格
		news = welcomeService.showNews(); //得到新闻
		anns = welcomeService.showAnns();//得到公告
		List<Parms> list = welcomeService.getList(); //得到首页需要的qq,email,phone
		for(Parms parms : list) {
			if("adminQQ".equals(parms.getTitle())) {
				sessionMap.put("adminQQ",parms.getValue());
			} else if("adminEmail".equals(parms.getTitle())) {
				sessionMap.put("adminEmail",parms.getValue());
			} else if("adminPhone".equals(parms.getTitle())) {
				sessionMap.put("adminPhone",parms.getValue());
			}
		}
		state = 1;
		//从邮箱进入重置密码后,删除临时表
		pwdTempDao.remove(pwd);
		return SUCCESS;
	}
	public String findPwd() throws Exception {
		Pattern emailer = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
		boolean flag = emailer.matcher(value).matches();
		//第一步 验证email是否正确
		if(flag) {
			//第二步 查看系统中是否存在这个email
			User user = welcomeService.findUserByEmail(value);
			if(user == null) {
				return "error";
			}
			//第三步 给用户id加密,保发存临时数据,确实重置密码时是同一条记录
			Long time = new Date().getTime();
			PwdTemp pwdTemp = new PwdTemp();
			pwdTemp.setUserId(user.getId());
			pwdTemp.setValidTime(time);
			Integer pwdId = (Integer) pwdTempDao.create(pwdTemp);
			//加id,和毫秒数加密
			id = (pwdId+56289)*250;
			String path = "http://127.0.0.1:8080/mt/";//本机测试
//			String path = "http://121.14.220.108/"; //用在正式布署
			String msg = "尊敬的："+user.getUsername()+"<br />您好<br />请击此处重置密码"+
			"<br />"+path+"reset.do?id="+id+"&validTime="+(time+98419)+
			"<br />或复制该链接至地址栏完成重置密码";
			//发送email
			EmailUtil.sendEmail("代理天下-用户重置密码",msg,value);
			state = 2;
			page = welcomeService.showPrice(pageNo, pageSize); //得到价格
			news = welcomeService.showNews(); //得到新闻
			anns = welcomeService.showAnns();//得到公告
			List<Parms> list = welcomeService.getList(); //得到首页需要的qq,email,phone
			for(Parms parms : list) {
				if("adminQQ".equals(parms.getTitle())) {
					sessionMap.put("adminQQ",parms.getValue());
				} else if("adminEmail".equals(parms.getTitle())) {
					sessionMap.put("adminEmail",parms.getValue());
				} else if("adminPhone".equals(parms.getTitle())) {
					sessionMap.put("adminPhone",parms.getValue());
				}
			}
			return SUCCESS;
		} else {
			return "error";
		}
	}
	public String backpwd() throws Exception {
		UserInfo userInfo = new UserInfo();
		String Agent = request.getHeader("User-Agent");
		StringTokenizer st = new StringTokenizer(Agent,";");
		st.nextToken();
		String userAgent = request.getHeader("User-Agent"); 
//		ClientInfo clientInfo = ClientInfoUtil.getClientInfo(userAgent);
//		System.out.println(clientInfo.getBrowserInfo());/** 得到用户的浏览器信息 */   
//		System.out.println(clientInfo.getOsInfo());/** 得到用户的操作系统信息 */  
		userInfo.setUserOs(System.getProperty("os.name"));  
		userInfo.setBrows(st.nextToken());
		userInfo.setUserName(System.getProperty("user.name"));
		InetAddress address;
		try {
			address = InetAddress.getLocalHost();
			userInfo.setIp(address.getHostAddress());  
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}  
		userInfo.setOsVersion(System.getProperty("os.version"));
		page = welcomeService.showPrice(pageNo, pageSize); //得到价格
		news = welcomeService.showNews(); //得到新闻
		anns = welcomeService.showAnns();//得到公告
		return SUCCESS;
	}
	public UserInfo getInfo() {
		return info;
	}

	public void setInfo(UserInfo info) {
		this.info = info;
	}
	public Answer getAnswer() {
		return answer;
	}
	public void setAnswer(Answer answer) {
		this.answer = answer;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public Integer getState() {
		return state;
	}
	public void setState(Integer state) {
		this.state = state;
	}
	public Page getPage() {
		return page;
	}
	public void setPage(Page page) {
		this.page = page;
	}
	public WelcomService getWelcomeService() {
		return welcomeService;
	}
	public void setWelcomeService(WelcomService welcomeService) {
		this.welcomeService = welcomeService;
	}
	public Parms getParms() {
		return parms;
	}
	public void setParms(Parms parms) {
		this.parms = parms;
	}
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getVerifycode() {
		return verifycode;
	}
	public void setVerifycode(String verifycode) {
		this.verifycode = verifycode;
	}

	public String getIp() {
		return ip;
	}
	public void setIp(String ip) {
		this.ip = ip;
	}
	public String getPort() {
		return port;
	}
	public void setPort(String port) {
		this.port = port;
	}
	
	public ProxyService getProxyService() {
		return proxyService;
	}
	public void setProxyService(ProxyService proxyService) {
		this.proxyService = proxyService;
	}

	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	
	
	public List<IndexPrice> getPriceList() {
		return priceList;
	}
	public void setPriceList(List<IndexPrice> priceList) {
		this.priceList = priceList;
	}
	
	public static void main(String[] args) {
		Pattern emailer = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
		boolean flag = emailer.matcher("4457@qqcom").matches();
		System.out.println(flag);
		
		
//		String ip="(1?\\d{1,2}|2[1-5][1-5])\\.(1?\\d{1,2}|2[1-5][1-5])\\.(1?\\d{1,2}|2[1-5][1-5])\\.(1?\\d{1,2}|2[1-5][1-5])"; 
//		
//		String test="119.84.113.55"; 
//		Pattern ipPattern=Pattern.compile(ip); 
//        Matcher matcher=ipPattern.matcher(test); 
//       System.out.println(test+" matches?"+matcher.matches()); 
//       
//       String portReq = "([0-9]|[1-9]\\d|[1-9]\\d{2}|[1-9]\\d{3}|[1-5]\\d{4}|6[0-4]\\d{3}|65[0-4]\\d{2}|655[0-2]\\d|6553[0-5])";	
//		Pattern ipPattern2 = Pattern.compile(portReq); 
//		Matcher matcher2=ipPattern.matcher("21"); 
//		System.out.println(test+" matches?"+matcher2.matches()); 

	}
	public Integer getPid() {
		return pid;
	}
	public void setPid(Integer pid) {
		this.pid = pid;
	}
	public Integer getNum() {
		return num;
	}
	public void setNum(Integer num) {
		this.num = num;
	}
	public Integer getPrice() {
		return price;
	}
	public void setPrice(Integer price) {
		this.price = price;
	}
	public List<News> getNews() {
		return news;
	}
	public void setNews(List<News> news) {
		this.news = news;
	}
	public List<Announcement> getAnns() {
		return anns;
	}
	public void setAnns(List<Announcement> anns) {
		this.anns = anns;
	}
	public Map<String, String> getObjMap() {
		return objMap;
	}
	public void setObjMap(Map<String, String> objMap) {
		this.objMap = objMap;
	}
	public PwdTempDao getPwdTempDao() {
		return pwdTempDao;
	}
	public void setPwdTempDao(PwdTempDao pwdTempDao) {
		this.pwdTempDao = pwdTempDao;
	}
	public Long getValidTime() {
		return validTime;
	}
	public void setValidTime(Long validTime) {
		this.validTime = validTime;
	}
	
	
}
